package com.wonderfulWeather.app.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.wonderfulWeather.app.R;
import com.wonderfulWeather.app.WeatherApplication;
import com.wonderfulWeather.app.model.County;
import com.wonderfulWeather.app.model.WeatherDB;
import com.wonderfulWeather.app.util.CommonUtility;
import com.wonderfulWeather.app.util.LocationListener;
import com.wonderfulWeather.app.util.LocationUtlity;
import com.wonderfulWeather.app.util.LogUtil;
import com.wonderfulWeather.app.view.Dialog;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import java.util.List;

public class SplashActivity extends Activity {
	boolean isFirstIn=false;
	private com.wonderfulWeather.app.util.LocationListener locationListener=null;
	private LocationClient mLocationClient = null;
	private BDLocationListener myListener = new MyLocationListener() ;
	
	private static final int GO_HOME=1000;
	private static final int GO_GUIDE=1001;
	
	private static final long SPLASH_DELAY_MILLIS=2000;

	
    private Handler mHandler=new Handler(){

		@Override
		public void handleMessage(Message msg)
		{
			Intent intent=null;
			switch(msg.what)
			{
				case GO_HOME:
					intent =new Intent(SplashActivity.this,WeatherActivity.class);
					startActivity(intent);
					finish();
					break;
				case GO_GUIDE:
					intent=new Intent(SplashActivity.this,GuideActivity.class);
					startActivity(intent);
					finish();
					break;
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.splash);
		//初始化
		init();
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if(hasFocus) {
			BeginRequestLocation(new LocationListener() {
				@Override
				public void getLocationSuccessed(County c)
				{
					LogUtil.d("onWindowFocusChanged","get location:"+c.getCounty());
					WeatherApplication.setCurrentCounty(c);
					//queryWeatherInfo(c.getCode());
				}

				@Override
				public void getLocationError(String ErrorCode) {
					//Toast.makeText(WeatherActivity.this,"为了更精准的获取天气信息，建议您打开WIFI网络",Toast.LENGTH_SHORT).show();
				}
			},getApplicationContext());
		}
		super.onWindowFocusChanged(hasFocus);
	}

	private void init()
	{
		SharedPreferences preferences=getSharedPreferences(CommonUtility.SHARED_PREF_NAME,MODE_PRIVATE);
		isFirstIn=preferences.getBoolean(CommonUtility.IS_FIRST_IN, true);
		if(!isFirstIn)
		{
			mHandler.sendEmptyMessageDelayed(GO_HOME, SPLASH_DELAY_MILLIS);
		}
		else
		{
			mHandler.sendEmptyMessageDelayed(GO_GUIDE,SPLASH_DELAY_MILLIS);
		}
	}

	private void initLocation(Context context)
	{
		mLocationClient = new LocationClient(context);     //声明LocationClient类
		mLocationClient.registerLocationListener( myListener );    //注册监听函数
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//设置定位模式
		option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(30*60*1000);//设置发起定位请求的间隔时间为5000ms
		option.setIsNeedAddress(true);//返回的定位结果包含地址信息
		option.setAddrType("all");
		option.setProdName(WeatherApplication.getContext().getResources().getString(R.string.app_name));
		option.setNeedDeviceDirect(true);//返回的定位结果包含手机机头的方向
		mLocationClient.setLocOption(option);
	}


	public void BeginRequestLocation(com.wonderfulWeather.app.util.LocationListener listener,Context context)
	{
		if(mLocationClient==null)
		{
			initLocation(context);
		}
		locationListener=listener;
		mLocationClient.start();
		LogUtil.d("location","Start get Location");
		if (mLocationClient != null && mLocationClient.isStarted()) {
			int code= mLocationClient.requestLocation();
			LogUtil.d("location","response code:"+code);
		}
		else {
			locationListener.getLocationError("LocSDK5:locClient is null or not started");
		}
	}

	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			mLocationClient.stop();
			LogUtil.d("location", "No Listener Method");
			if (location == null) return ;
			LogUtil.d("location","get Location over,type:"+location.getLocType());
			String city="",district="";

			//离线定位
			if(location.getLocType()==BDLocation.TypeOffLineLocationNetworkFail)
			{
				mLocationClient.requestOfflineLocation();
			}

			//离线
			if (location.getLocType()== BDLocation.TypeOffLineLocation)
			{
				city=location.getCity();
				district=location.getDistrict();
			}

			//缓存
			if(location.getLocType()==BDLocation.TypeCacheLocation)
			{
				city=location.getCity();
				district=location.getDistrict();
			}

			//在线定位
			if (location.getLocType() == BDLocation.TypeNetWorkLocation){

				city=location.getCity();
				district=location.getDistrict();
			}
			//城市判断并回调
			if(!TextUtils.isEmpty(city) || !TextUtils.isEmpty(city))
			{
				//是否有对应的区县
				List<County> clist = WeatherDB.getInstance(WeatherApplication.getContext()).QueryCounty(district.replace("区",""));
				if (clist.size() == 0) { //是否有对应的城市
					clist=WeatherDB.getInstance(WeatherApplication.getContext()).QueryCounty( city.replace("市",""));
				}

				if(clist.size()>0) {
					locationListener.getLocationSuccessed(clist.get(0));
				}
			}
			else
			{
				Toast.makeText(WeatherApplication.getContext(), "为了更快更精准的获取天气信息，建议打开WIFI网络", Toast.LENGTH_LONG).show();
			}
		}
	}
}
